package com.example.grid.webserviceclient;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.transport.HttpsTransportSE;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.xmlpull.v1.XmlPullParserException;

public class WebServiceHelper {
	private static String userId="bas4509240011";//"bas4501030273";
	private static String passWord="45092400112816202@gxwst";//"45010302732816202@gxwst";
	private static String soapHeader="MySoapHeader";

	//public static String WSDL_URI = "https://59.211.16.98:19438/BasWebService.asmx?WSDL";//"https://59.211.16.98:19438/BasWebService.asmx?WSDL";//wsdl 的uri
	private static String namespace = "http://microsoft.com/webservices/";//namespace
	private static String host="59.211.16.98";
	private static String file="/BasWebService.asmx?WSDL";
	private static int timeout=10000;
	private static int port=19438;

	public static String getUrl()
	{
		return "https://" + host + ":" + port + file;
	}

	/**
	 * @param sNameSpace 命名空间
	 * @return Soap头
	 */
	public static Element[] getSoapHeader(String sNameSpace)
	{
		Element[] header = new Element[1];
		header[0] = new Element().createElement(sNameSpace, soapHeader);

		Element username = new Element().createElement(sNameSpace, "Uname");
		username.addChild(Node.TEXT, userId);
		header[0].addChild(Node.ELEMENT, username);

		Element pass = new Element().createElement(sNameSpace,"Password");
		pass.addChild(Node.TEXT, passWord);
		header[0].addChild(Node.ELEMENT, pass);
		return header;
	}


	/**
	 * @param methodName  方法名
	 * @param list  参数列表
	 * @return webService的返回
	 */
	public static Object requestWebService(String methodName,  List <PropertyInfo>list) throws IOException,XmlPullParserException,NoSuchAlgorithmException, KeyManagementException{
		SoapObject request = new SoapObject(namespace, methodName);
		if (list!=null && list.size()>0) {
			for (PropertyInfo propertyInfo : list) {
				request.addProperty(propertyInfo.getName(),propertyInfo.getValue());
			}
		}
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapSerializationEnvelope.VER12);
		envelope.headerOut=getSoapHeader(namespace);
		envelope.bodyOut = request;//由于是发送请求，所以是设置bodyOut
		envelope.dotNet = true;//由于是.net开发的webservice，所以这里要设置为true
		SSLConnection.allowAllSSL();
		HttpsTransportSE transportSE = new HttpsTransportSE(host, port, file, timeout);
		transportSE.call(namespace + methodName, envelope);
		return envelope.getResponse();
	};




}
